package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.domain.AppEarnRouseSort;
import com.lebang.example.AppEarnRouseSortExample;
import com.lebang.mapper.AppEarnRouseSortMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

import static com.lebang.service.DownAppService.getMaxKey;

/**
 * 数据源排序
 *
 * @Author hwq
 * @Date 2020-03-13
 */
@Service
public class AppEarnRouseSortService extends BaseService<AppEarnRouseSort, Integer, AppEarnRouseSortExample> {
    @Autowired
    private RedisClient redisClient;
    private static final String KEY = "AppEarnRouseSort";

    public static String getKey(String appStore) {
        return KEY+":"+appStore;
    }

    /**
     * 根据次数 获取当前要做什么
     *
     * @param count
     * @return
     */
    public AppEarnRouseSort getByCount(Integer count, String appStore) {
        if(!redisClient.hexists(getKey(appStore),"1")){
            appStore="all";
        }
        Optional<String> str = redisClient.Optionalhget(getKey(appStore), count.toString());
        return str.map(value ->
                JSON.parseObject(value, AppEarnRouseSort.class)).orElse(null);
    }



    public void init(String appStore) {
        redisClient.del(getKey(appStore));
        AtomicInteger i = new AtomicInteger(0);
        AppEarnRouseSortExample example=new AppEarnRouseSortExample();
        example.createCriteria().andAppStoreEqualTo(appStore);
        List<AppEarnRouseSort> appVideoSorts = this.selectByExample(example);
        appVideoSorts.forEach(s -> {
            if (s.getCount() > i.get()) {
                i.set(s.getCount());
            }
            redisClient.hset(getKey(appStore), s.getCount().toString(), JSON.toJSONString(s));
        });
        redisClient.del(getMaxKey(appStore));
        if(i.get()!=0){
            redisClient.set(getMaxKey(appStore), i.toString());
        }

    }

    /**
     * 用户是否能完成对应的版本
     *
     * @param appEarnRouseSort
     * @param version
     * @return
     */
    public boolean check(AppEarnRouseSort appEarnRouseSort, Integer version) {

        return version>=appEarnRouseSort.getVersion()  ;
    }
}
